const fs = require("fs/promises");
const path = require("path");
const { isDirectory } = require("./isDirectory");
/**
 * 文件夹重命名
 * @param {*} dir
 * @param {*} getRename
 * @param {*} deep
 * @returns
 */
exports.renameFolder = async function (dir, getRename, deep = false) {
  if (typeof getRename !== "function") {
    console.log("重命名方法有误");
    return;
  }
  const files = await fs.readdir(dir).catch((err) => {
    console.log("读取目录下文件夹失败", err.message);
    return [];
  });

  for (const file of files) {
    const oldPath = path.join(dir, file);

    // 判断是否为文件夹
    const isDir = await isDirectory(oldPath);
    if (isDir) {
      const newname = getRename(file);
      const newPath = path.join(dir, newname);
      if (newname !== file) {
        await fs
          .rename(oldPath, newPath)
          .then(() => {
            console.log("重命名成功", file, "===>", newname);
          })
          .catch((err) => {
            console.log("重命名失败", err.message);
          });
      }
      if (deep) {
        // 是否深度执行
        await exports.renameFolder(newPath, getRename, true);
      }
    }
  }
};
